<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Pay;
use think\Config;

/**
 * 收费接口
 * @ApiInternal
 */
class Feeorder extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\FeeOrder;
    }

    /**
     * 预览
     */
    public function preview()
    {
        $this->success('success', $this->get_fee_items());
    }

    /**
     * 支付
     */
    public function submit()
    {
        $user_fee_items = json_decode($this->auth->fee_items, true) ?: [];
        if (!$user_fee_items) {
            $this->error('暂未设置收费项目,请联系管理员');
        }

        $row = $this->model->where(['user_id' => $this->auth->id])->find();
        if ($row && $row['is_pay'] == 1) {
            $this->error('您已经支付过了');
        }

        if ($this->auth->openid == '') {
            $this->error('请先微信授权', null, 3);
        }

        $items = $this->get_fee_items();

        $data = [
            'order_sn'     => date("Ymdhis") . mt_rand(10000, 99999),
            'user_id'      => $this->auth->id,
            'nickname'     => $this->auth->nickname,
            'items'        => json_encode($items['items']),
            'total_amount' => $items['total_amount']
        ];

        $row ? $row->save($data) : $this->model->save($data);

        $result = Pay::minipay([
            'sn' => $data['order_sn'], 'pay_money' => $data['total_amount']
        ], $this->auth->openid, 'feeorder');

        $this->success('success', $result);
    }


    /**
     * 申请退保证金
     */
    public function refund()
    {
        $row = $this->model->where(['user_id' => $this->auth->id, 'is_pay' => 1])->find();
        if (!$row) {
            $this->error('您还未交保证金');
        }

        if ($row->is_refund == 1 || $row->state == 1) {
            $this->error('保证金已退');
        }

        if ($row->state == 0) {
            $this->error('申请正在审核中');
        }

        $days = floor((time() - $row['paytime']) / 86400);
        if ($days < 365) {
            $this->error((365 - $days) . '天后可申请退还');
        }

        $row->state = 0;
        $row->save();

        $this->success('申请成功,请耐心等待审核');
    }

    /**
     * 保证金扣除记录
     */
    public function log()
    {
        $row = $this->model->where(['user_id' => $this->auth->id, 'is_pay' => 1])->find();
        if (!$row) {
            $this->error('您还未交保证金');
        }

        $list = \app\common\model\FeeLog::where(['user_id' => $this->auth->id])->order('createtime desc')->paginate();

        $this->success('success', $list);
    }

    protected function get_fee_items()
    {
        $config = Config::get('site');
        $fee_items = $config[$this->auth->role . '_item'];

        $total_amount = 0;
        $user_fee_items = json_decode($this->auth->fee_items, true) ?: [];

        $items = [];
        foreach ($fee_items as $key => $val) {
            $item = [ 'item' => $key, 'amount' => 0, 'desc' => $val ];
            foreach ($user_fee_items as $v) {
                if ($key == $v['item']) {
                    $item['amount'] = $v['amount'];
                }
            }
            $total_amount += $item['amount'];
            $items[] = $item;
        }

        return [
            'items'         => $items,
            'total_amount'  => round($total_amount, 2)
        ];
    }
}